#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
服务类对象模型
定义系统中的各类服务及其配置
"""

from sqlalchemy import Column, Integer, String, Text, Boolean, ForeignKey, DateTime, JSON, FLOAT
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from typing import Dict, Any, List, Optional
import enum
from models.base import Base
from services.ai_service_factory import ServiceType


class ServiceStatus(str, enum.Enum):
    """服务状态枚举"""
    ACTIVE = "active"        # 激活
    INACTIVE = "inactive"    # 未激活
    MAINTENANCE = "maintenance"  # 维护中
    ERROR = "error"         # 错误状态


class ServiceCategory(str, enum.Enum):
    """服务分类枚举"""
    AI_ANALYSIS = "ai_analysis"        # AI分析服务
    EXTRACT_LOCATION = "extract_location"  # 地理信息服务
    POLLUTION_TYPE_RECOGNITION = "pollution_type_recognition"  # 污染类型识别服务
    DATA_PROCESSING = "data_processing"  # 数据处理服务
    REPORT_GENERATION = "report_generation"  # 报告生成服务
    SYSTEM_MANAGEMENT = "system_management"  # 系统管理服务


class ServiceProvider(str, enum.Enum):
    """服务提供商枚举"""
    ZHIPU = "zhipu"           # 智谱AI
    OPENAI = "openai"         # OpenAI
    QWEN = "qwen"             # 通义千问


class ServiceClass(Base):
    """服务类对象模型"""
    
    __tablename__ = "service_classes"
    # 主键字段
    id = Column(Integer, primary_key=True, comment="服务类ID")

    # 基本信息字段
    service_id = Column(String(50), unique=True, nullable=False, comment="服务编号")
    name = Column(String(100), nullable=False, comment="服务名称")
    description = Column(Text, comment="服务描述")
    category = Column(String(20), default=ServiceType.AI_ANALYSIS, comment="服务选取的类型")
    
    # 模型配置字段
    provider = Column(String(20), default=ServiceProvider.ZHIPU, comment="服务提供商")
    model_code = Column(String(100), comment="模型代码")
    max_tokens = Column(Integer, default=4096, comment="最大输出长度")
    temperature = Column(FLOAT, default=0.1, comment="模型问答")
    
    # 提示词配置字段
    prompt_template_id = Column(Integer, ForeignKey("prompt_templates.id"), comment="关联的提示词模板ID")
    
    # 服务配置字段
    is_active = Column(Boolean, default=True, comment="是否激活")
    config = Column(JSON, comment="服务配置参数")
    
    # 使用统计
    usage_count = Column(Integer, default=0, comment="使用次数")
    last_used_at = Column(DateTime, comment="最后使用时间")
    
    # 状态字段
    status = Column(String(20), default=ServiceStatus.ACTIVE, comment="服务状态")
    error_message = Column(Text, comment="错误信息")
    
    # 时间戳
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关联关系
    prompt_template = relationship("PromptTemplate", backref="service_classes", foreign_keys=[prompt_template_id])
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        result = super().to_dict()
        # 添加提示词模板信息
        if self.prompt_template:
            result['prompt_template'] = {
                'id': self.prompt_template.id,
                'name': self.prompt_template.name,
                'description': self.prompt_template.description
            }
        return result
    
    def get_service_config(self) -> Dict[str, Any]:
        """获取服务配置"""
        config = {
            'service_id': self.service_id,
            'name': self.name,
            'provider': self.provider,
            'model_code': self.model_code,
            'category': self.category,
            'is_active': self.is_active,
            'config': self.config or {}
        }
        
        # 添加提示词配置
        if self.prompt_template:
            config['prompt_template'] = {
                'id': self.prompt_template.id,
                'name': self.prompt_template.name,
                'content': self.prompt_template.content,
                'output_format': self.prompt_template.output_format,
                'parameters': [param.to_dict() for param in self.prompt_template.parameters]
            }
        
        return config
    
    def update_usage_stats(self):
        """更新使用统计"""
        self.usage_count += 1
        self.last_used_at = func.now()


class ServiceInstance(Base):
    """服务实例模型"""
    
    __tablename__ = "service_instances"
    # 主键字段
    id = Column(Integer, primary_key=True, comment="服务实例ID")

    # 外键关联
    service_class_id = Column(Integer, ForeignKey("service_classes.id"), nullable=False, comment="关联的服务类ID")
    user_id = Column(Integer, ForeignKey("user.id"), comment="创建用户ID")
    
    # 实例信息
    instance_name = Column(String(100), nullable=False, comment="实例名称")
    instance_config = Column(JSON, comment="实例配置参数")
    
    # 状态字段
    is_active = Column(Boolean, default=True, comment="是否激活")
    status = Column(String(20), default=ServiceStatus.ACTIVE, comment="实例状态")
    
    # 使用统计
    usage_count = Column(Integer, default=0, comment="使用次数")
    last_used_at = Column(DateTime, comment="最后使用时间")
    
    # 时间戳
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关联关系
    service_class = relationship("ServiceClass", backref="instances", foreign_keys=[service_class_id])
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        result = super().to_dict()
        # 添加服务类信息
        if self.service_class:
            result['service_class'] = {
                'id': self.service_class.id,
                'service_id': self.service_class.service_id,
                'name': self.service_class.name,
                'provider': self.service_class.provider,
                'model_name': self.service_class.model_name
            }
        return result


class ServiceUsageLog(Base):
    """服务使用日志模型"""
    
    __tablename__ = "service_usage_logs"
    # 主键字段
    id = Column(Integer, primary_key=True, comment="服务使用日志ID")

    # 外键关联
    service_class_id = Column(Integer, ForeignKey("service_classes.id"), nullable=False, comment="服务类ID")
    service_instance_id = Column(Integer, ForeignKey("service_instances.id"), comment="服务实例ID")
    user_id = Column(Integer, ForeignKey("user.id"), comment="用户ID")
    
    # 使用信息
    request_data = Column(JSON, comment="请求数据")
    response_data = Column(JSON, comment="响应数据")
    execution_time = Column(Integer, comment="执行时间(毫秒)")
    token_count = Column(Integer, comment="使用的token数量")
    cost = Column(String(50), comment="费用")
    
    # 结果信息
    status = Column(String(20), default="success", comment="执行状态")
    error_message = Column(Text, comment="错误信息")
    
    # 时间戳
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    
    # 关联关系
    service_class = relationship("ServiceClass", backref="usage_logs", foreign_keys=[service_class_id])
    service_instance = relationship("ServiceInstance", backref="usage_logs", foreign_keys=[service_instance_id])
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        result = super().to_dict()
        # 过滤敏感信息
        if 'request_data' in result:
            result['request_data_preview'] = str(result['request_data'])[:100] + "..." if len(str(result['request_data'])) > 100 else str(result['request_data'])
        return result


class ServiceConfigTemplate(Base):
    """服务配置模板模型"""
    
    __tablename__ = "service_config_templates"
    
    # 基本信息字段
    name = Column(String(100), nullable=False, comment="模板名称")
    description = Column(Text, comment="模板描述")
    service_category = Column(String(20), comment="服务分类")
    
    # 配置字段
    config_schema = Column(JSON, comment="配置模式定义")
    default_config = Column(JSON, comment="默认配置")
    
    # 使用统计
    usage_count = Column(Integer, default=0, comment="使用次数")
    
    # 时间戳
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return super().to_dict()


# 预定义的服务类配置
DEFAULT_SERVICE_CLASSES = [
    {
        "service_id": "extract_info",
        "name": "地址信息抽取",
        "description": "从信访内容中抽取街道、区县、详细地址、详细对象等信息",
        "category": ServiceType.EXTRACT_INFO,
        "provider": ServiceProvider.ZHIPU,
        "model_name": "zhipu",
        "model_code": "glm-4-flash",
        "is_active": True,
        "config": {
            "max_tokens": 2000,
            "temperature": 0.7,
            "timeout": 30
        }
    },
    {
        "service_id": "specify_analysis",
        "name": "规范分析",
        "description": "根据定义判断回复内容是否合规",
        "category": ServiceType.COMPLIANCE_CHECK,
        "provider": ServiceProvider.ZHIPU,
        "model_name": "zhipu",
        "model_code": "glm-4-flash",
        "is_active": True,
        "config": {
            "max_tokens": 1000,
            "temperature": 0.3,
            "timeout": 30
        }
    },
    {
        "service_id": "sentiment_analysis",
        "name": "情感分析",
        "description": "根据定义判断信访内容的情感",
        "category": ServiceType.SENTIMENT_ANALYSIS,
        "provider": ServiceProvider.ZHIPU,
        "model_name": "zhipu",
        "model_code": "glm-4-flash",
        "is_active": True,
        "config": {
            "max_tokens": 1500,
            "temperature": 0.5,
            "timeout": 30
        }
    }
]